package com.shanghaionstar;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;

import com.onstar.cn.common.log.LogManager;
import com.onstar.cn.framework.utils.ViewInjectUtils;

import java.util.ArrayList;
import java.util.List;

import static android.support.v4.content.ContextCompat.checkSelfPermission;

/**
 * @author 7828wc
 * @ClassName: BaseFragment
 * @Description: Fragment 基类
 * @date 2015年7月27日 下午2:43:13
 */
public abstract class BaseFragment extends Fragment {
    public LogManager log = LogManager.getInstance();
    private View contentView = null;
    private boolean isFirstLoad = true;

    public String getFragmentTag() {
        return getClass().getSimpleName();
    }

    @Override
    public void onResume() {
        log.d("current fragment is --->" + getFragmentTag());
        super.onResume();
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (contentView == null) {
            contentView = inflater.inflate(getLayoutId(), container, false);
            injectView(contentView);
            isFirstLoad = true;
        } else {
            onResumeView(contentView);
            isFirstLoad = false;
        }
        LogManager.getInstance().d("current fragment:::" + getClass().getName());
        return contentView;
    }

    public boolean isFirstLoad() {
        return isFirstLoad;
    }

    public View getContentView() {
        return contentView;
    }

    public abstract int getLayoutId();

    /**
     * @param @param view 设定文件
     * @return void 返回类型
     * @throws
     * @Title: onResumeView
     * @Description: 返回Fragment的已绘制View对象
     */
    public void onResumeView(View view) {
        ViewGroup parent = (ViewGroup) view.getParent();
        if (null != parent) {
            parent.removeView(view);
        }
    }

    /**
     * @param @param view 设定文件
     * @return void 返回类型
     * @throws
     * @Title: injectView
     * @Description: 注入View
     */
    public void injectView(View view) {
        ViewInjectUtils.injectByFragment(this, view);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // 执行Activity 的OnCreate方法回调此方法
        ((BaseFragmentActivity) getActivity()).setCurrentFragmentTag(getClass().getSimpleName());
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        // 当Fragment的layout被销毁时调用
    }

    @Override
    public void onDetach() {
        super.onDetach();
        // 当Fragment从Activity中删除调用
    }

    /**
     * @param @return 设定文件
     * @return LogManager 返回类型
     * @throws
     * @Title: getLogger
     * @Description: 日志管理器
     */
    public LogManager getLogger() {
        return ((BaseFragmentActivity) getActivity()).getLogger();
    }

    /**
     * @param @return 设定文件
     * @return void 返回类型
     * @throws
     * @Title: back
     * @Description: 返回上一次Fragment页面
     */
    public void back() {
        if (getActivity() != null) {
            BaseFragmentActivity baseFragmentActivity = ((BaseFragmentActivity) getActivity());
            if (!baseFragmentActivity.isFinishing() && this.isResumed()) {
                getActivity().onBackPressed();
            }
        }
    }

    /**
     * @param @param fragment 设定文件
     * @return void 返回类型
     * @throws
     * @Title: remove
     * @Description: 删除制定Fragment
     */
    public void remove(Fragment fragment) {
        ((BaseFragmentActivity) getActivity()).removeFragment(((BaseFragmentActivity) getActivity()).getFManager(),
                fragment);
    }

    /**
     * @param @param view 设定文件
     * @return void 返回类型
     * @throws
     * @Title: btnBackClick
     * @Description: 返回键监听
     */
    public void btnBackClick(View view) {
        view.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                back();
            }
        });
    }


    public ProgressDialog showLoadProgress() {
        ProgressDialog progDialog = new ProgressDialog(getActivity());
        progDialog.setMessage(getString(R.string.waiting));
        return progDialog;
    }

    public void dismissDialog(ProgressDialog dialog) {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }


    public interface InteractiveMsg {
        void handleMsg(Message message);
    }

    public void addFragment(FragmentManager fm, Fragment fragment, int container, String tag) {
        FragmentTransaction fragmentTransaction = fm.beginTransaction();
        fragmentTransaction.replace(container, fragment, tag);

        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commitAllowingStateLoss();

        Fragment fragmentTest = fm.findFragmentByTag(tag);
        Log.d("test", "" + fragmentTest);
    }

    private final int permissionRequestCode = 110;
    private PermissionCall mPermissionCall;
   /* 处理权限问题*/

    /**
     * 对子类提供的申请权限方法
     *
     * @param permissions 申请的权限
     */
    public void requestRunTimePermissions(String[] permissions, PermissionCall call) {
        if (permissions == null || permissions.length == 0)
            return;
        mPermissionCall = call;
        if ((Build.VERSION.SDK_INT < Build.VERSION_CODES.M) || checkPermissionGranted(permissions)) {
            //提示已经拥有权限
            mPermissionCall.requestSuccess();
        } else {
            //申请权限
            requestPermission(findDeniedPermissions(permissions), permissionRequestCode);
        }
    }

    public boolean checkPermissionGranted(String... permissions) {
        boolean result = true;
        for (String p : permissions) {
            if (checkSelfPermission(getActivity(), p) != PackageManager.PERMISSION_GRANTED) {
                result = false;
                break;
            }
        }
        return result;
    }

    private boolean shouldShowRequestPermissionRationale(String[] permissions) {
        boolean flag = false;
        for (String p : permissions) {
            if (shouldShowRequestPermissionRationale(p)) {
                flag = true;
                break;
            }
        }
        return flag;
    }

    private void requestPermission(final String[] permissions, final int requestCode) {
        try {
//            if (shouldShowRequestPermissionRationale(permissions)) {
//                new AlertDialog.Builder(getActivity())
//                        .setTitle(R.string.attention)
//                        .setMessage(R.string.content_to_request_permission)
//                        .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                requestPermissions(permissions, requestCode);
//                            }
//                        }).show();
//            } else {
//                requestPermissions( permissions, permissionRequestCode);
//            }
                requestPermissions( permissions, permissionRequestCode);
        } catch (Exception e) {
            Log.e("", e.getMessage());
        }

    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == permissionRequestCode) {
            if (verifyPermissions(grantResults)) {
                mPermissionCall.requestSuccess();
                mPermissionCall = null;
            } else {
                mPermissionCall.refused();
                mPermissionCall = null;
            }
        }
    }

    public boolean verifyPermissions(int[] grantResults) {
        // At least one result must be checked.
        if (grantResults.length < 1) {
            return false;
        }

        // Verify that each required permission has been granted, otherwise return false.
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    public interface PermissionCall {
        //申请成功
        void requestSuccess();

        //拒绝
        void refused();
    }

    public String[] findDeniedPermissions(String... permission) {
        List<String> denyPermissions = new ArrayList<>();
        for (String value : permission) {
            if (checkSelfPermission(getActivity(), value) != PackageManager.PERMISSION_GRANTED) {
                denyPermissions.add(value);
            }
        }
        return denyPermissions.toArray(new String[denyPermissions.size()]);
    }
}
